package net.yxsoft.controller.pc.sysmgt.infrastructure;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import net.yxsoft.bean.JsTreeNode;
import net.yxsoft.bean.JsTreeNodeFieldKey;
import net.yxsoft.bean.UserSearchModel;
import net.yxsoft.controller.pc.sysmgt.common.interceptor.SignInterceptor;
import net.yxsoft.enumclass.SexEnumCls;
import net.yxsoft.enumclass.StateEnumCls;
import net.yxsoft.enumclass.TsUserTypeEnumCls;
import net.yxsoft.kit.Helper;
import net.yxsoft.kit.JsTreeNodeKit;
import net.yxsoft.render.PoiRender;
import net.yxsoft.resource.AuthuserRes;
import net.yxsoft.controller.pc.sysmgt.common.AuthController;
import net.yxsoft.model.infrastructure.TsGroup;
import net.yxsoft.model.infrastructure.TsUser;
import net.yxsoft.resource.CodeRes;
import net.yxsoft.resource.Res;
import net.yxsoft.service.infrastructure.CodeService;
import net.yxsoft.service.infrastructure.UserService;
import rapid.core.Authuser;
import net.yxsoft.bean.BSTablePage;
import rapid.core.TResult;
import rapid.jfinal.Pagination;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * Created by mlb on 2016/5/25.
 */
public class UserController extends AuthController {

  private static final CodeService codeService = CodeService.INSTANCE;
  private UserService userService = UserService.INSTANCE;

  /**
  * @MethodName: index
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:23
  * @author jhf
  */
  public void index() {
    Authuser user = getLoginUser();

    setAttr("isAdmin", user.get(AuthuserRes.KEY_TYPE).equals(TsUserTypeEnumCls.TYPE_0));
    setAttr("SexddlSource", SexEnumCls.COLLECTS_CHOOSE);
    setAttr("SexradSource", SexEnumCls.COLLECTS_DEFAULTS);

    render("user.html");
  }


  /**
  * @MethodName: indexsrc
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:23
  * @author jhf
  */
  public void indexsrc() {
    Authuser user = getLoginUser();

    setAttr("isAdmin", true);
    setAttr("SexddlSource", SexEnumCls.COLLECTS_CHOOSE);
    setAttr("SexradSource", SexEnumCls.COLLECTS_DEFAULTS);

    render("user2.html");
  }
  /**
  * @MethodName: getUsers
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:23
  * @author jhf
  */
  public void getUsers() {
    BSTablePage bsTablePage = BSTablePage.init(this);

    Kv cond = Kv.create();
    if(StrKit.notBlank(getPara("loginId"))) {
      cond.set("U.login_id LIKE ", "'%" + getPara("loginId") + "%'");
    }

    if(StrKit.notBlank(getPara("name"))) {
      cond.set("U.name LIKE ", "'%" + getPara("name") + "%'");
    }
    if(StrKit.notBlank(getPara("sex"))) {
      cond.set("U.sex =", "'" + getPara("sex") + "'");
    }

    if(StrKit.notBlank(getPara("userCode"))) {
      cond.set("U.user_typ LIKE ", "'%" + getPara("userCode") + "%'");
    }
    if(StrKit.notBlank(getPara("roleIds"))) {
      cond.set("UR.ROLE_ID in ", "('" + getPara("roleIds").replace(",","','") + "')");
    }
    if(StrKit.notBlank(getPara("groups"))) {
      cond.set("UG.GROUP_ID in ", "('" + getPara("groups").replace(",","','") + "')");
    }

    Kv cond1 = Kv.by("cond", cond);
    Authuser user = getLoginUser();

    if(!user.getLoginId().equals("admin")) {
      String groupIdStr=user.get(AuthuserRes.KEY_GROUP_IDS);
      if(StrKit.notNull(groupIdStr)){
        groupIdStr=groupIdStr.replaceAll(",","','");
      }
     // cond1.set("gid", user.get(AuthuserRes.KEY_GROUP_IDS));
      cond1.set("gid", "'"+groupIdStr+"'");
    }


    renderJson(userService.query("user.userPageSelect", cond1, Pagination.by(this)));
  }

/**
* @MethodName: getUsers2
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:23
* @author jhf
*/
  public void getUsers2() {
    BSTablePage bsTablePage = BSTablePage.init(this);

    Kv cond = Kv.create();
    if(StrKit.notBlank(getPara("loginId"))) {
      cond.set("U.login_id LIKE ", "'%" + getPara("loginId") + "%'");
    }

    if(StrKit.notBlank(getPara("name"))) {
      cond.set("U.name LIKE ", "'%" + getPara("name") + "%'");
    }
    if(StrKit.notBlank(getPara("sex"))) {
      cond.set("U.sex =", "'" + getPara("sex") + "'");
    }

    if(StrKit.notBlank(getPara("userCode"))) {
      cond.set("U.user_typ LIKE ", "'%" + getPara("userCode") + "%'");
    }
    if(StrKit.notBlank(getPara("roleIds"))) {
      cond.set("UR.ROLE_ID in ", "('" + getPara("roleIds").replace(",","','") + "')");
    }
    if(StrKit.notBlank(getPara("groups"))) {
      cond.set("UG.GROUP_ID in ", "('" + getPara("groups").replace(",","','") + "')");
    }

    Kv cond1 = Kv.by("cond", cond);
    Authuser user = getLoginUser();


    renderJson(userService.query("user.userPageSelect", cond1, Pagination.by(this)));
  }
  /**
  * @MethodName: getUpdateUserById
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:23
  * @author jhf
  */
    @Before(POST.class)
    public void getUpdateUserById() {
      TsUser model = new TsUser().findById(this.getPara("Id"));
      renderJson(model);
    }

  /**
  * @MethodName: addUser
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:23
  * @author jhf
  */
  @Before({POST.class,SignInterceptor.class})
  public void addUser() {
    TsUser _m = getModel(TsUser.class, "", true);
    if(_m != null) {
      renderJson(userService.addUser(_m, getLoginUser()));
    } else {
      renderJson(-99);
    }
  }

  /**
  * @MethodName: updateUser
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:24
  * @author jhf
  */
  @Before({POST.class, SignInterceptor.class})
  public void updateUser() {
    TsUser _m = getModel(TsUser.class, "", true);
    if(_m != null) {
      renderJson(userService.updateUser(_m, getLoginUser()));
    } else {
      renderJson(-99);
    }
  }


    /**
    * @MethodName: removeUsers
    * @Description: 根据主键集合删除用户
    * @param:
    * @return void
    * @throws
    * @date 2023/8/31 15:24
    * @author jhf
    */
  @Before(POST.class)
  public void removeUsers() throws SQLException {
    String[] _ids = getPara("ids").split(",");
    renderJson(userService.removeUsers(_ids));
  }

  public void getAllRoleInfo() {
    renderJson(userService.getAllRoleInfo());
  }

  public void getUserRoleRelationByUserId() {
    String _id = this.getPara("Id");

    if(_id != null) {
      renderJson(userService.getUserRoleRelationByUserId(_id));
    }
  }
  /**
  * @MethodName: setUserRoleRelation
  * @Description:
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:24
  * @author jhf
  */
  @Before(POST.class)
  public void setUserRoleRelation() {

    String _id = this.getPara("userId");
    String[] _roleids = this.getPara("roleIds").split(",");
    if(_id != null) {
      renderJson(userService.setUserRoleRelation(_id, _roleids,getLoginUser()));
    }
  }
/**
* @MethodName: getjsTreeByGroup
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void getjsTreeByGroup() throws NoSuchMethodException, SecurityException, InvocationTargetException, IllegalAccessException {
    JsTreeNodeFieldKey tnfk = new JsTreeNodeFieldKey("Id", "Name", "Pid");
    tnfk.setLeafKey("Pid");
    tnfk.setLeafValue("0");

    //判断是否是系统管理员，否就显示有权限的机构列表
    List<TsGroup> grouplist =new ArrayList<>();
    Authuser loginUser = getLoginUser();
    if(!loginUser.getLoginId().equals("admin")) {
      String groupNames = loginUser.get("GROUP_NAMES").toString();
      String[] groupNameArr = groupNames.split(",");
      StringJoiner groupJoiner = new StringJoiner(",");
      for (Object groupName:groupNameArr) {
        groupJoiner.add("?");
      }
      grouplist = TsGroup.dao.find("SELECT * FROM TS_GROUP WHERE NAME IN("+groupJoiner+") ORDER BY SORT_ID",groupNameArr);
    }else{
       grouplist = TsGroup.dao.find("SELECT * FROM TS_GROUP ORDER BY SORT_ID");
    }


    List<JsTreeNode> treelist = JsTreeNodeKit.SerializeJsTreeData(tnfk, grouplist);

    renderJson(treelist);

  }
/**
* @MethodName: getUserGroupRelationByUserId
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void getUserGroupRelationByUserId() {
    String _id = this.getPara("Id");

    if(_id != null) {
      renderJson(userService.getUserGroupRelationByUserId(_id).toArray());
    }
  }
/**
* @MethodName: setUserGroupRelation
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  @Before(POST.class)
  public void setUserGroupRelation() {

    String _id = this.getPara("userId");
    String[] _groupids = (this.getPara("groupIds")).split(",");
    if(_id != null) {
      renderJson(userService.setUserGroupRelation(_id, _groupids,getLoginUser()));
    }
  }
/**
* @MethodName: getUserGroupDataRelationByUserId
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void getUserGroupDataRelationByUserId() {
    String _id = this.getPara("Id");

    if(_id != null) {
      renderJson(userService.getUserGroupDataRelationByUserId(_id).toArray());
    }
  }
/**
* @MethodName: setUserGroupDataRelation
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  @Before(POST.class)
  public void setUserGroupDataRelation() {
    String _id = this.getPara("userId");
    String _strgroupids = this.getPara("groupIds");

    if(StrKit.notBlank(_strgroupids)) {
      String[] _groupids = _strgroupids.split(",");
      if(_id != null) {
        renderJson(userService.setUserGroupDataRelation(_id, _groupids));
      }
    } else {
      renderJson(userService.setUserGroupDataRelation(_id, null));
    }
  }
/**
* @MethodName: changeState
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void changeState() throws IllegalAccessException {
    String _userids = getPara("userids");
    String _statestr = getPara("state");
    int _result = 0;
    if(!StrKit.isBlank(_userids) && !StrKit.isBlank(_statestr)) {

      StateEnumCls state = StateEnumCls.getObject(StateEnumCls.class, _statestr);

      _result = userService.changeState(_userids.split(","), state,getLoginUser());
    }
    renderJson(_result);
  }


/**
* @MethodName: changeLogin
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void changeLogin() throws IllegalAccessException {
    String _userids = getPara("userids");
    String _statestr = getPara("state");
    int _result = 0;
    if(!StrKit.isBlank(_userids) && !StrKit.isBlank(_statestr)) {



      _result = userService.changeLogin(_userids.split(","), _statestr,getLoginUser());
    }
    renderJson(_result);
  }
/**
* @MethodName: resetPassword
* @Description:
* @param:
* @return void
* @throws
* @date 2023/8/31 15:24
* @author jhf
*/
  public void resetPassword() {
    String _userids = getPara("userids");
    int _result = 0;
    if(!StrKit.isBlank(_userids)) {
      _result = userService.resetPassword(_userids.split(","),getLoginUser());
    }
    renderJson(_result);

  }

  /**
  * @MethodName: exportUsers
  * @Description: 导出
  * @param:
  * @return void
  * @throws
  * @date 2023/8/31 15:24
  * @author jhf
  */
  public void exportUsers() {
    UserSearchModel _model = new UserSearchModel();

    _model.setLoginId(this.getPara("loginId", ""));
    _model.setName(this.getPara("name", ""));
    _model.setSex(this.getPara("sex", ""));
    // _model.setUserType(this.getPara("userType", ""));
    _model.setUserCode(this.getPara("userCode", ""));

    String[] _roleIds = this.getParaValues("roleIds");

    StringBuilder _strroleIds = new StringBuilder();

    if(StrKit.notBlank(_roleIds)) {
      for(int i = 0; i < _roleIds.length; i++) {
        if(i == 0) {
          _strroleIds.append("'" + _roleIds[i] + "'");
        } else {
          _strroleIds.append(",'" + _roleIds[i] + "'");
        }
      }
    }

    _model.setRoleIds(_strroleIds.toString());

    String _groups = this.getPara("groups", "");
    _model.setGroups(_groups);

    List<TsUser> ls = userService.exportUsers(_model);
    String[] clumns = {"login_id", "name", "roleName", "user_typ_cn"};
    String[] heades = {"账号", "名称", "角色", "用户类型"};
    render(PoiRender.me(ls).fileName("users.xls").sheetName("用户信息").headers(heades).columns(clumns).cellWidth(5000).headerRow(1));
  }




  public void auditS(){
    renderJson(userService.auditS(getPara("userids").split(",")));
  }
}
